#include "driver_saadc.h"
#include "boards.h"
#include "app_util_platform.h"
#include "nrf_drv_saadc.h"


#define ADC_REF_VOLTAGE_IN_MILLIVOLTS		(1200)
#define ADC_DIV         					(4095)

void saadc_callback(nrf_drv_saadc_evt_t const * p_event)
{
    if (p_event->type == NRF_DRV_SAADC_EVT_DONE)
    {
    }
}

void driver_saadc_init(void)
{
	ret_code_t err_code;
	
	// SAADC Init
	nrf_drv_saadc_config_t saadc_config = 
	{
		.resolution			= NRF_SAADC_RESOLUTION_12BIT,
		.oversample			= NRF_SAADC_OVERSAMPLE_DISABLED,
		.interrupt_priority	= APP_IRQ_PRIORITY_LOW,
	};
	
	err_code = nrf_drv_saadc_init(&saadc_config, saadc_callback);
    APP_ERROR_CHECK(err_code);
	
	// TEMP ADC Init
    nrf_saadc_channel_config_t channel_config =
	{
		.resistor_p = NRF_SAADC_RESISTOR_DISABLED,         
		.resistor_n = NRF_SAADC_RESISTOR_DISABLED,         
		.gain       = NRF_SAADC_GAIN1_2,                   
		.reference  = NRF_SAADC_REFERENCE_INTERNAL,        
		.acq_time   = NRF_SAADC_ACQTIME_10US,              
		.mode       = NRF_SAADC_MODE_SINGLE_ENDED,         
		.pin_p      = (nrf_saadc_input_t)(NRF_SAADC_INPUT_AIN3),          
		.pin_n      = NRF_SAADC_INPUT_DISABLED             
	};
	
	err_code = nrf_drv_saadc_channel_init(TEMP_ADC_CHANNEL_NUM, &channel_config);
    APP_ERROR_CHECK(err_code);
	
	nrf_gpio_cfg_output(TEMP_VCC_PIN);
	nrf_gpio_cfg_output(TEMP_ENABLE_PIN);
	
	nrf_gpio_pin_set(TEMP_VCC_PIN);
	nrf_gpio_pin_set(TEMP_ENABLE_PIN);
	
}

bool driver_saadc_temp_get(uint32_t *value)
{
	ret_code_t err_code;
	double mv;
	double temp;
	
    nrf_saadc_value_t adc_result = 0;
	
	err_code = nrf_drv_saadc_sample_convert(TEMP_ADC_CHANNEL_NUM, &adc_result);
    APP_ERROR_CHECK(err_code);
	
	mv = (double)(((double)ADC_REF_VOLTAGE_IN_MILLIVOLTS)/((double)ADC_DIV)*adc_result);
	
	// y = -5.1939x + 1098.6
	// x = (y-1098.6)/-5.1939
	temp = (mv-1098.6)/-5.1939;
	
	*value = temp*100;
	
	return true;
}

